import axios from "axios";
import {errorMsg, load, queryState} from "./global";
import {actions as WindowAction} from '../common/window/store';
import {actions as UserAction} from '@/store/common/user'
import store from "../store";
import {reviewObject} from "@/util/ObjectUtil";
import qs from 'qs';
import {clearUserInfo} from "@/util/UserUtil";
/* 访问外网 */
const RequestHttp = axios.create({
    timeout: 1000 * 30,
    withCredentials: true,
    baseURL: '/pay',
    maxRedirects: 0,
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'X-Requested-With': 'XMLHttpRequest'
    }
})
export {RequestHttp};
const Http = axios.create({
    timeout: 1000 * 30,
    withCredentials: true,
    baseURL: '/api',
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    }
})

Http.interceptors.request.use(config => {
    /**
     * 过滤空ParamsValue
     */
    config.params = reviewObject(config.params);
    /**
     *  获取 Token ↓ ↓ ↓
     *  先从sessionStorage获取.
     *  若不存在,则从redux获取然后赋值给sessionStorage.
     *  @type {string}
     */
    let token = queryState('user.token');
    let VCode = queryState('window.VerificationCode');
    if (VCode) {
        config.headers['code'] = VCode
        store.dispatch(WindowAction.saveVerificationCode(''));
    }
    if (config.method.toLowerCase() === 'get') {
        config.paramsSerializer = function (params) {
            return qs.stringify(params, {arrayFormat: 'repeat'})
        }
    }
    // sessionStorage.removeItem('VerificationCode');
    if (!token) {
        let thisToken = sessionStorage.getItem('token');
        if (thisToken) {
            config.headers['token'] = thisToken
        }
    } else {
        config.headers['token'] = token
    }
    return config;
})

Http.interceptors.response.use((res) => {
    /* 登录后的Token及短时间内过期Token无缝衔接 */
    if (
        (res.data.token !== undefined && res.data.token !== null)
        ||
        res.headers['token']
    ) {
        sessionStorage.setItem('token', res.headers['token']);
        store.dispatch(UserAction.toRefreshToken(res.data.token));
        console.log(`Token令牌已于${new Date()}完成无缝刷新~！`)
    }
    /* 接管路由控制 */
    if (window._ROUTER_ !== undefined && window._ROUTER_ !== null) {
        let code = parseInt(res.data.code);
        switch (code) {
            // 验证码错误
            case 100:
                break;
            case 300:
            case 301:
            case 303:
            case 350:
                clearUserInfo();
                window._ROUTER_.push("/login");
                break;
            case 500:
                console.log(res.data.message);
                break;
            case 404:
                window._ROUTER_.push("/404");
                break;
            case 200:
            default:
                break;
        }
    }
    if (res.data.success === false) {
        errorMsg(res.data.message)
    }
    return res.data;
}, error => {
    console.log(error)
    load(false);
    return {success: false};
})


export default Http;
